package com.sophialex.health.record.views.baseinfo;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.widgets.Composite;

import com.sophialex.health.common.platform.SuperContext;
import com.sophialex.health.common.platform.pojo.Geography;
import com.sophialex.health.common.platform.util.CustomGenerator;
import com.sophialex.health.person.vo.HrPerson;
import com.sophialex.health.record.Messages;
import com.sophialex.health.record.common.Constants;
import com.sophialex.health.record.common.util.DataSource;
import com.sophialex.health.record.common.utils.CommonUtils;
import com.sophialex.health.record.common.validate.TextVerifyListener;
import com.sophialex.health.record.lktable.KtableColumnDesc;
import com.sophialex.health.record.lktable.cellEdit.FamilyMemberCellEdit;
import com.sophialex.health.record.lktable.cellstyle.FamilyMemberCellStyleProvider;
import com.sophialex.health.record.lktable.join.FamilyJoinOutValue;
import com.sophialex.health.record.lktable.traverse.FamilyTraverseStrategy;
import com.sophialex.health.record.ui.baseinfo.FamilyUI;
import com.sophialex.health.system.frame.dialog.DialogManager;
import com.sophialex.health.system.frame.resource.RcpResourceManager;
import com.sophialex.health.system.lktable.KTableCellSelectionListener;
import com.sophialex.health.system.lktable.LKTable;
import com.sophialex.health.system.lktable.SWTX;
import com.sophialex.health.system.lktable.LKTableUtil.ECellEditType;

public class FamilyView extends FamilyUI {
	public FamilyView() {
	}
    
	public static final String ID = "com.sophialex.health.record.views.baseinfo.FamilyView"; //$NON-NLS-1$
    
	public void createPartControl(Composite parent) {
		super.createPartControl(parent);
		setActionControl();
		initTable();
		addListner();
		
	}
	
	
	private void addListner(){
		familyMemberTable.addMouseListener(new MouseAdapter() {
			public void mouseDoubleClick(MouseEvent e) {
				if (familyMemberTable.getDataList() == null
						|| familyMemberTable.getDataList().size() == 0)
					doAddItem();
			}
		});
		familyMemberTable.addTraverseListener(new TraverseListener() {
			public void keyTraversed(TraverseEvent e) {
				if (e.keyCode == SWT.ESC) {
					doDel();
				} else if ((e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR)) {
					if ((familyMemberTable.getDataList() == null || familyMemberTable
							.getDataList().size() == 0)) {
						doAddItem();
					}
				} else if (e.keyCode == SWT.ARROW_DOWN) {
					if (familyMemberTable.getDataList() != null
							&& familyMemberTable.getDataList().size() > 0) {
						if (familyMemberTable.getDataList().indexOf(
								familyMemberTable.getSelection()) == familyMemberTable
								.getDataList().size() - 1) {
							doAddItem();
						}
					} else {
						doAddItem();
					}
				}
			}
		});

		familyMemberTable.addCellSelectionListener(new KTableCellSelectionListener() {
			public void fixedCellSelected(int col, int row, int statemask) {
			
			}

			public void cellSelected(int col, int row, int statemask) {
				KtableColumnDesc desc = desclist.get(col);
				HrPerson select = (HrPerson) familyMemberTable.getSelection();
				
				if(select.getId()!=null  && select.getId().longValue() == hrPerson.getId().longValue()){
					return;
				}
				if (desc.getField().equals("perRelaMaster")) {
					getPerson(col);
				}
			}
		});
		
		txt_jzzmj.addVerifyListener(new TextVerifyListener(1));
		txt_rjjzmj.addVerifyListener(new TextVerifyListener(1));
	}
	private void initTable(){
		familyMemberTable = new LKTable(composite_4, SWT.V_SCROLL
										| SWT.H_SCROLL | SWTX.EDIT_ON_KEY | SWTX.WRAP);
		familyMemberTable.setBackground(RcpResourceManager.getColor(SWT.COLOR_WHITE));
	
		desclist = initColumns();
		if (desclist != null) {
			for (int i = 0; i < desclist.size(); i++) {
				KtableColumnDesc desc = desclist.get(i);
				familyMemberTable.doAddColumn(i, desc.getColumnTitle(),
						desc.getField(), desc.getWidth(), desc.getAlign(), desc
								.getEditType(), desc.isCellEdit(), desc
								.isCanSetValue());
				if (desc.getEditBase() != null) {
					familyMemberTable.addCellEditBase(desc.getField(), desc
							.getEditBase());
				}
			}
		}
		familyMemberTable.setHeaderHeight(Constants.TABLE_HEAD_HEIGHT);
		familyMemberTable.setCellStyleProvider(new FamilyMemberCellStyleProvider());
		familyMemberTable.setTraverseStrategy(new FamilyTraverseStrategy(familyMemberTable, this));
		familyMemberTable.setJoinOut(new FamilyJoinOutValue());
		familyMemberTable.exeLKTable(HrPerson.class);
		familyMemberTable.setInput(hrPersonList);
	}
	
	private List<KtableColumnDesc> initColumns(){
		List<KtableColumnDesc> list = new ArrayList<KtableColumnDesc>();
		list.add(new KtableColumnDesc(Messages.getString("HrPersonAssist.0"), "name", 120,SWTX.ALIGN_HORIZONTAL_LEFT, ECellEditType.textBox, true,true, null));
		list.add(new KtableColumnDesc(Messages.getString("HrPersonAssist.1"), "sex", 90,SWTX.ALIGN_HORIZONTAL_LEFT, ECellEditType.textBox, false,false, null));
		list.add(new KtableColumnDesc(Messages.getString("HrPersonAssist.2"), "birthday", 120,SWTX.ALIGN_HORIZONTAL_LEFT, ECellEditType.textBox, false,false, null));
		list.add(new KtableColumnDesc(Messages.getString("HrPersonAssist.3"), "idno", 180,SWTX.ALIGN_HORIZONTAL_LEFT, ECellEditType.textBox, false,false, null));
		list.add(new KtableColumnDesc(Messages.getString("HrPersonAssist.4"), "adminUserId", 120,SWTX.ALIGN_HORIZONTAL_LEFT, ECellEditType.textBox, false,false, null));
		list.add(new KtableColumnDesc(Messages.getString("Family.Member.2"), "perRelaMaster", 120,SWTX.ALIGN_HORIZONTAL_LEFT, ECellEditType.comboBox_dict, true,true, new FamilyMemberCellEdit()));
		familyMemberTable.doAddComboSet(5,SuperContext.dictCache.getCodesByName("RELATION"));
		list.add(new KtableColumnDesc(Messages.getString("HrPersonAssist.5"), "cadress", 330,SWTX.ALIGN_HORIZONTAL_LEFT, ECellEditType.textBox, false,false, null));
		return list;
	}
	@Override
	protected void doPrint() {
//		String messgae = validateUtil.getMessage().toString();
//		if(!validateUtil.isValidate()){
//			DialogManager.invokeTitleDig(messgae);
//		}
	}
	protected void doAdd() {
		switchView(FamilyInfoViewState.ADD_VIEW);
		annotionProcessor.updateUI(hrFamily,null);
		removeAllMember();
		hrPerson = null;
		CommonUtils.initDsGeography(getCombo_jwh(), treeObj);
	}
 
	protected void doDel() {
		boolean flag = false;
		if(hrFamily == null || hrFamily.getId() == null){
			DialogManager.invokeWarnDlg(Messages.getString("FamilyUI_INFO.9")); 
			return;
		}
		if(DialogManager.invokeConfirmDlg(Messages.getString("FamilyUI_INFO.3") + getTxt_hzxm().getText() + Messages.getString("FamilyUI_INFO.4"))) {
			flag = DataSource.hrFamilyService.deleteFamily(hrFamily.getId());
			if(flag) {
				DialogManager.invokeInfoDlg(Messages.getString("FamilyUI_INFO.5"));
			} else {
				DialogManager.invokeInfoDlg(Messages.getString("FamilyUI_INFO.6"));
			}
		}
		switchView(FamilyInfoViewState.SHOW_VIEW);	
		annotionProcessor.updateUI(hrFamily,null);
		removeAllMember();
		hrPerson = null;
		CommonUtils.initDsGeography(getCombo_jwh(), treeObj);
	}
	protected void doExit() {
		getViewSite().getPage().hideView(this);

	
	}
	@Override
	protected void doEdit() {
		if(hrFamily == null || hrFamily.getId() == null){
			DialogManager.invokeWarnDlg(Messages.getString("FamilyUI_INFO.8")); 
			return;
		}
		switchView(FamilyInfoViewState.EDIT_VIEW);
		changeState(false,0);
	}
	@Override
	public void setFocus() {
		// TODO Auto-generated method stub
	}
	@Override
	protected void doCancel() {
		switchView(FamilyInfoViewState.SHOW_VIEW);
		changeState(true,2);
	}


	/**
	 * 保存家庭信息
	 */
	protected void doSave() {
		if(hrPerson == null || hrPerson.getId() == null){
			DialogManager.invokeWarnDlg(Messages.getString("FamilyUI_INFO.12")); 
			return;
		}
		boolean flag = false;

		if(!validateUtil.isValidate()){
//			System.out.println(result.get("count") + "    -----------");
			validateUtil.openWarn();
			
			return;
		}
		try{
			hrFamily.setCommonPojo(CommonUtils.getCommonPojo());
			Geography geography = (Geography) getCombo_jwh().getTreeItemData();
			if(geography!=null){
				hrFamily.setHamlet(Long.valueOf(geography.getfTreebh()));
			}
			List<Object> objectList = familyMemberTable.getDataList();
			for(Object obj : objectList) {
				if(!doCheck((HrPerson) obj))
					return ;
			}
			List<HrPerson> pList = new ArrayList<HrPerson>();
			for(int i = 0; i < objectList.size(); i++) {
				pList.add((HrPerson)objectList.get(i));
			}
			if(hrFamily.getId()!=null){
				flag = DataSource.hrFamilyService.updateFamily(hrFamily,pList);
			}else{
				hrFamily.setId(CustomGenerator.generator());
				if(hrFamily.getFamilyMasterId() ==null ){
					hrFamily.setFamilyMasterId(hrPerson.getId());
				}
				
				flag = DataSource.hrFamilyService.saveFamily(hrFamily,pList);
			}
			
			if(flag){
				DialogManager.invokeInfoDlg(Messages.getString("FamilyUI_INFO.0")); 
			}else{
				DialogManager.invokeInfoDlg(Messages.getString("FamilyUI_INFO.1")); 
			}
			switchView(FamilyInfoViewState.SHOW_VIEW);
			
		}catch(Exception e){
			DialogManager.invokeInfoDlg(Messages.getString("FamilyUI_INFO.1") + e.getMessage()); 
			e.printStackTrace();
		}
		

		
	}
	void switchView(FamilyInfoViewState state) {
		viewstate = state;
		setActionControl();
	}

	public boolean doCheck() {
		if (StringUtils.isBlank(hrFamily.getFamilyMasterName())) {
			DialogManager.invokeWarnDlg(Messages.getString("FamilyUI_ERROR.5")); 
			getTxt_hzxm().setFocus();
			return false;
		}
		return true;

	}


}
